package product

import (
	"apiExample/auth"
	"apiExample/common"
	"errors"
	"fmt"
)

type exportProductRequest struct {
	Start int32 `json:"start,omitempty"`
	Count int32 `json:"count,omitempty"`
}

type Product struct {
	 ProductId int64 `json:"product_id"`
	 Version int32 `json:"version"`
	 ProductName string `json:"product_name"`
	 Price int64 `json:"price"`
	 Status int32 `json:"status"`
	 ClassId int32 `json:"class_id"`
	 ClassName string `json:"class_name"`
	 UnitId int32 `json:"unit_id"`
	 UnitName string `json:"unit_name"`
	 CreateTime int64 `json:"create_time"`
	 CreatePid int64 `json:"create_pid"`
}

type exportProductResult struct {
	Result int32 `json:"result"`
	Errmsg string `json:"errmsg"`
	End bool `json:"end"`
	Products []*Product `json:"products"`
}
/*
	11.1 导出商品
*/
func ExportProduct(start, count int32) ([]*Product, error) {
	token, err := auth.GetAccessToken()
	if err != nil {
		return  nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/product/export?access_token=%s", common.ApiUrl, token)

	req := &exportProductRequest{
		Start: start,
		Count: count,
	}

	rsp := &exportProductResult{}
	if err := common.HttpPostData(url, req ,rsp); err != nil {
		return nil, err
	}

	if rsp.Result != 0 {
		return  nil, errors.New(fmt.Sprintf("Server respone not ok, result=%v,msg=%s", rsp.Result, rsp.Errmsg))
	}
	return rsp.Products, nil
}

type productInfo struct {
	ProductId int64 `json:"product_id,omitempty"`
	Version int32 `json:"version,omitempty"`
}
type getProductDetailRequest struct {
	ProductInfos []*productInfo `json:"product_infos"`
}
type getProductDetailResult struct {
	Result int32 `json:"result"`
	Errmsg string `json:"errmsg"`
	Products []*Product `json:"products"`
}
/*
	11.2 批量获取商品详情
*/
func GetProductDetail(req *getProductDetailRequest) ([]*Product, error)  {
	token, err := auth.GetAccessToken()
	if err != nil {
		return  nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/product/details?access_token=%s", common.ApiUrl, token)


	rsp := &getProductDetailResult{}
	if err := common.HttpPostData(url, req ,rsp); err != nil {
		return nil, err
	}

	if rsp.Result != 0 {
		return  nil, errors.New(fmt.Sprintf("Server respone not ok, result=%v,msg=%s", rsp.Result, rsp.Errmsg))
	}
	return rsp.Products, nil
}